<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="操作时间" prop="operateTime">
        <el-date-picker clearable
                        v-model="queryParams.operateTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择操作时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="退款编号" prop="refundNo">
        <el-input
            v-model="queryParams.refundNo"
            placeholder="请输入退款编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="患者姓名" prop="patientName">
        <el-input
            v-model="queryParams.patientName"
            placeholder="请输入患者姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:refund:add']"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:refund:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="refundList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="操作时间" align="center" prop="operateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.operateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退款编号" align="center" prop="refundNo"/>
      <el-table-column label="患者姓名" align="center" prop="patientName"/>
      <el-table-column label="就诊卡号" align="center" prop="id"/>
      <el-table-column label="来源" align="center" prop="source"/>
      <el-table-column label="业务类型" align="center" prop="bizType"/>
      <el-table-column label="退款方式" align="center" prop="refundType"/>
      <el-table-column label="退款金额" align="center" prop="amount"/>
      <el-table-column label="支付状态" align="center" prop="refundStatus">
        <template #default="scope">
          <span
              :style="{ color: scope.row.refundStatus === '已支付' ? 'green' : scope.row.refundStatus === '未支付' ? 'red' : 'inherit' }">
            {{ scope.row.refundStatus }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="卡内余额" align="center" prop="balance"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:refund:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:refund:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改退款记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-divider content-position="center">患者信息</el-divider>
      <el-form ref="refundRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="患者姓名" prop="patientName">
          <el-select v-model="form.patientName" placeholder="请选择患者" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in patientsList" :key="index" :value="item.id"
                       :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证件类型">
          <el-input v-model="zjlx" disabled/>
        </el-form-item>
        <el-form-item label="微信昵称">
          <el-input v-model="wxnc" disabled/>
        </el-form-item>
        <el-form-item label="就诊地址">
          <el-input v-model="jzrdz" disabled/>
        </el-form-item>
        <el-form-item label="就诊卡号" prop="id">
          <el-input v-model="form.id" placeholder="请输入就诊卡号" disabled/>
        </el-form-item>
        <el-form-item label="证件号码">
          <el-input v-model="zjhm" disabled/>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="sj" disabled/>
        </el-form-item>
        <div class="avatar-uploader">
          <!-- 文本内容 -->
          <span class="text">患者头像</span>

          <!-- 圆形相框 -->
          <div
              class="avatar-frame"
              @click="triggerFileInput"
          >
            <!-- 显示上传的头像或默认空白 -->
            <img
                v-if="avatarUrl"
                :src="avatarUrl"
                alt="用户头像"
                class="avatar-image"
            />
            <div v-else class="empty-frame">
            </div>

            <!-- 隐藏的文件输入 -->
            <input
                type="file"
                ref="fileInput"
                @change="handleFileChange"
                accept="image/*"
                style="display: none;"
            />
          </div>
        </div>
        <el-form-item label="关系" style="padding-top: 20px">
          <el-input v-model="gx"/>
        </el-form-item>
      </el-form>
      <el-divider content-position="center">订单信息</el-divider>
      <el-form ref="refundRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="退款金额">
          <el-input v-model="form.amount"/>
        </el-form-item>
        <el-form-item label="退款方式" prop="refundType">
          <el-input v-model="form.refundType"/>
        </el-form-item>
        <el-form-item label="卡内余额" prop="balance">
          <el-input v-model="form.balance" placeholder="请输入卡内余额" disabled/>
        </el-form-item>
        <el-form-item label="支付状态" prop="status">
          <el-radio-group v-model="form.refundStatus">
            <el-radio
                v-for="(item, index) in status"
                :key="index"
                :label="item.label"
            >{{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="退款编号" prop="refundNo">
          <el-input v-model="form.refundNo"/>
        </el-form-item>
        <el-form-item label="操作时间" prop="operateTime">
          <el-date-picker clearable
                          v-model="form.operateTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="来源" prop="source">
          <el-input v-model="form.source" placeholder="请输入来源"/>
        </el-form-item>
        <el-form-item label="业务类型" prop="bizType">
          <el-input v-model="form.bizType" placeholder="请输入业务类型"/>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="input" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>

    </el-dialog>
  </div>
</template>

<script setup name="Refund">
import {listRefund, getRefund, delRefund, addRefund, updateRefund} from "@/api/system/refund"
import {ref, watch} from "vue";
import {listPatients, getPatients, updatePatients} from "@/api/system/patients.js"
import {listAppointments} from "@/api/system/appointments.js";

const {proxy} = getCurrentInstance()

const refundList = ref([])
const feeRecordsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const checkedFeeRecords = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const input = ref('')
const gx = ref('本人')
const zjlx = ref('身份证号')
const wxnc = ref('七尾Sam')
const jzrdz = ref('北京市朝阳区**路**号**小区')
const zjhm = ref('371890199507070909')
const sj = ref('15678900988')
const fileInput = ref(null);
const avatarUrl = ref('');
const patientid = ref('')
const patientsList=ref([])
const status = ref([{
  "label": "未支付",
  "value": "未支付"
}, {
  "label": "已支付",
  "value": "已支付"
}])
// 触发文件选择
const triggerFileInput = () => {
  fileInput.value.click();
};

// 处理文件选择
const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      alert('请选择图片文件');
      return;
    }

    // 创建文件URL并显示
    avatarUrl.value = URL.createObjectURL(file);

    // 这里可以添加实际上传逻辑
    // uploadAvatar(file);
  }
};
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    operateTime: null,
    refundNo: null,
    patientName: null,
    source: null,
    bizType: null,
    refundType: null,
    amount: null,
    refundStatus: null,
    balance: null,
    ifok: null
  },
  rules: {
    refundNo: [
      {required: true, message: "退款编号不能为空", trigger: "blur"}
    ],
    patientName: [
      {required: true, message: "患者姓名不能为空", trigger: "blur"}
    ],
  }
})

const {queryParams, form, rules} = toRefs(data)

/** 查询退款记录列表 */
function getList() {
  loading.value = true
  listRefund(queryParams.value).then(async response => {
    refundList.value = response.rows
    total.value = response.total
    loading.value = false
    await Promise.all(refundList.value.map(async (item, index) => {
      const patientData = await getPatients(item.patientName);
      refundList.value[index].patientName = patientData.data.name;
      refundList.value[index].balance = patientData.data.cardBalance;
    }));
    patientsList.value =(await listPatients(queryParams.value)).rows
    console.log(patientsList.value)
  })
}
watch(() => form.value.patientName, (newValue, oldValue) => {
  if (typeof newValue=="number") {
    getPatients(newValue).then(async response => {
      patientid.value = newValue
      wxnc.value = response.data.wechatNickname
      jzrdz.value = response.data.address
      zjhm.value = response.data.idCard
      sj.value = response.data.phone
      form.value.balance = response.data.cardBalance
    });
  }
})
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    operateTime: null,
    refundNo: null,
    patientName: null,
    id: null,
    source: null,
    bizType: null,
    refundType: null,
    amount: null,
    refundStatus: null,
    balance: null,
    ifok: null,
  }
  feeRecordsList.value = []
  proxy.resetForm("refundRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  zjhm.value = ''
  sj.value = ''
  wxnc.value = ''
  jzrdz.value =''
  open.value = true
  title.value = "添加退款记录"
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getRefund(_id).then(response => {
    form.value = response.data
    feeRecordsList.value = response.data.feeRecordsList
    open.value = true
    title.value = "修改退款记录"
    getPatients(response.data.patientName).then(response => {
      patientid.value = response.data.id
      form.value.patientName = response.data.name
      zjhm.value = response.data.idCard
      sj.value = response.data.phone
      wxnc.value = response.data.wechatNickname
      jzrdz.value = response.data.address
      form.value.balance = response.data.cardBalance
    })
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["refundRef"].validate(async valid => {
    if (valid) {
      if (form.value.id != null) {
        try {
          if (form.value.ifok === 0 && form.value.refundStatus === "已支付") {
            // 1. 准备数据
            const a = await getPatients(patientid.value);
            a.data.cardBalance = form.value.balance + form.value.amount;
            // 2. 更新form数据
            form.value = {
              ...form.value,
              ifok: 1,
              balance: form.value.balance + form.value.amount,
              patientName: patientid.value,
              feeRecordsList: feeRecordsList.value
            };
            // 3. 执行更新操作
            if (form.value.id != null) {
              // 先更新患者信息
              await updatePatients(a.data);
              // 再更新退款记录
              await updateRefund(form.value);
              proxy.$modal.msgSuccess("修改成功");
            }
          }else {
            form.value.patientName = patientid.value
            await updateRefund(form.value);
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          }
        } catch (error) {
          console.error("操作失败:", error);
          proxy.$modal.msgError("操作失败: " + error.message);
        }
      } else {
        await addRefund(form.value);
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getList();
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除退款记录编号为"' + _ids + '"的数据项？').then(function () {
    return delRefund(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}

/** 门诊消费记录序号 */
function rowFeeRecordsIndex({row, rowIndex}) {
  row.index = rowIndex + 1
}

/** 门诊消费记录添加按钮操作 */
function handleAddFeeRecords() {
  let obj = {}
  obj.patientName = ""
  obj.orderNo = ""
  obj.operateTime = ""
  obj.source = ""
  obj.bizType = ""
  obj.feeType = ""
  obj.payType = ""
  obj.amount = ""
  obj.payStatus = ""
  feeRecordsList.value.push(obj)
}

/** 门诊消费记录删除按钮操作 */
function handleDeleteFeeRecords() {
  if (checkedFeeRecords.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的门诊消费记录数据")
  } else {
    const feeRecordss = feeRecordsList.value
    const checkedFeeRecordss = checkedFeeRecords.value
    feeRecordsList.value = feeRecordss.filter(function (item) {
      return checkedFeeRecordss.indexOf(item.index) == -1
    })
  }
}

/** 复选框选中数据 */
function handleFeeRecordsSelectionChange(selection) {
  checkedFeeRecords.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/refund/export', {
    ...queryParams.value
  }, `refund_${new Date().getTime()}.xlsx`)
}

getList()
</script>
<style scoped>
.avatar-uploader {
  display: flex;
  align-items: center;
  gap: 10px;
}

.text {
  font-size: 15px;
  padding-right: 32px;
  padding-left: 10px;
  font-weight: 600;

}

.avatar-frame {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 2px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  position: relative;
  transition: all 0.3s ease;
  background-color: #E4EFFE;
}


.empty-frame {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  color: #ccc;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>